//
//  FashionController.m
//  WANNA
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 浮夸. All rights reserved.
//

#import "FashionController.h"
#import "FashionModel.h"
#import "fashionCell.h"
#import "LDTNetWorkRequestManager.h"
#import "LDTCycleView.h"
#import "fashionCycleModel.h"
#import "fashionDetialController.h"
#import "LORefresh.h"
@interface FashionController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView *fashTable;
@property (nonatomic,strong)NSMutableArray *fashionArray;


@property (nonatomic,strong)LDTCycleView *cycleView;

@property (nonatomic,strong)NSMutableArray *cycleArray;


///请求内容起始条数
@property(nonatomic,strong)NSString *start;
//hader属性
@property(nonatomic,strong)LORefresh *headerRefresh;

@end

@implementation FashionController
-(NSMutableArray *)cycleArray {
    if (!_cycleArray) {
        _cycleArray = [NSMutableArray new];
    }
    return _cycleArray;
}
-(NSMutableArray *)fashionArray {
    if (!_fashionArray) {
        _fashionArray = [NSMutableArray new];
    }
    return _fashionArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setViews];
    self.start = @"0";
    [self loadDataFromServerStart:self.start];
    [self setDelegate];
}
-(void)setViews {
    self.fashTable = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    [self.view addSubview:self.fashTable];
    [self.fashTable registerNib:[UINib nibWithNibName:@"fashionCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.fashTable dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    self.cycleView = [[LDTCycleView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 230) InterVal:3];
    
    [self.fashTable addSubview:self.cycleView];

    
    //添加下拉刷新
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        
        [weakSelf.fashionArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadDataFromServerStart:@"0"];
    }];
    self.headerRefresh = [self.tableView defaultHeader];
    
    //上拉加载
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeFooterDefault) refreshingBlock:^{
        
        NSInteger count = weakSelf.fashionArray.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        
        [weakSelf loadDataFromServerStart:weakSelf.start];
        
    }];

}
-(void)setDelegate {
    self.fashTable.delegate = self;
    self.fashTable.dataSource = self;
  
}
-(void)loadDataFromServerStart:(NSString *)start {
        NSData *dataa=[NSJSONSerialization dataWithJSONObject:@{@"curVersion":@"4.0.4",@"channelId":@"2-17",@"limit":@12,@"language":@"zh-Hans",@"refreshType":@1,@"localNum":@12,@"lastTime":self.start,@"startTime":@0,@"ruleTime":@"1462265286g"}  options:NSJSONWritingPrettyPrinted error:nil];
    NSString *paras = [[NSString alloc]initWithData:dataa encoding:NSUTF8StringEncoding];
    NSString *parasStr = [paras stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet decimalDigitCharacterSet]];
    
    [LDTNetWorkRequestManager requestURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://new.yohoboys.com/yohoboyins/v4/channel/contentList?parameters=%@",parasStr]] Method:LDT_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                               
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dict in jsonDict[@"data"][@"content"]) {
            FashionModel *model = [FashionModel new];
            [model setValuesForKeysWithDictionary:dict];
            [self.fashionArray addObject:model];
        }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.fashTable reloadData];
    });
}];
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:@{@"channelId":@"2-17",@"curVersion":@"4.0.4",@"language":@"zh-Hans"}options:NSJSONWritingPrettyPrinted error:nil];
    NSString *params = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSString *parStr = [params stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet decimalDigitCharacterSet]];
    

    [LDTNetWorkRequestManager requestURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://new.yohoboys.com/yohoboyins/v4/channel/banner?parameters=%@",parStr]] Method:LDT_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array= jsonDict[@"data"];
        
        for (NSDictionary *dic in array) {
            fashionCycleModel *model = [[fashionCycleModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.image]]];
            
            [self.cycleArray addObject:image];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            self.cycleView.imgNameArray = self.cycleArray;
        });
        
    }];

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    fashionDetialController *bfashionVC = [[fashionDetialController alloc]init];
    FashionModel *model = self.fashionArray[indexPath.row];
    
    bfashionVC.publishUrl = model.publishURL;
    bfashionVC.titl = model.title;
    [self.navigationController pushViewController:bfashionVC animated:YES];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.fashionArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    fashionCell *cell = [self.fashTable dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model = self.fashionArray[indexPath.row];
    
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    
    tableView.tableHeaderView=headerView;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 350;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
